from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator

class Tag(models.Model):
    name = models.CharField(max_length=20, unique=True)

    def __str__(self):
        return self.name

class Category(models.Model):
    name = models.CharField(max_length=50, unique=True)  # 例如：外卖、堂食、自制等

    def __str__(self):
        return self.name

class Recipe(models.Model):
    DIFFICULTY_CHOICES = [
        ('easy', '简单'),
        ('medium', '中等'),
        ('hard', '困难'),
    ]
    PRICE_TIER_CHOICES = [
        ('low', '便宜'),
        ('medium', '中等'),
        ('high', '较贵'),
    ]

    title = models.CharField("菜名", max_length=100)
    description = models.TextField("简介", blank=True)
    ingredients = models.TextField("材料（结构化文本）", blank=True)
    steps = models.TextField("步骤说明", blank=True)
    notes = models.TextField("注意事项", blank=True)
    link = models.URLField("教程链接", blank=True)

    tags = models.ManyToManyField(Tag, blank=True)
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True)
    # 如果是堂食，需要填写 location；如果是外卖，需要填写 shop_name（表单层会校验）
    location = models.CharField("位置（堂食）", max_length=200, blank=True)
    shop_name = models.CharField("店铺（外卖）", max_length=200, blank=True)

    # 新增属性
    rating = models.DecimalField(
        "评分", max_digits=2, decimal_places=1,
        validators=[MinValueValidator(0), MaxValueValidator(5)],
        null=True, blank=True,
        help_text="0.0 - 5.0"
    )
    difficulty = models.CharField("难易度", max_length=10, choices=DIFFICULTY_CHOICES, blank=True)
    estimated_minutes = models.PositiveIntegerField("预计耗时（分钟）", null=True, blank=True)
    price_tier = models.CharField("价格档次", max_length=10, choices=PRICE_TIER_CHOICES, blank=True)
    is_takeaway_available = models.BooleanField("是否可外卖", default=False)
    health_index = models.PositiveSmallIntegerField(
        "健康指数", validators=[MinValueValidator(1), MaxValueValidator(5)],
        null=True, blank=True,
        help_text="1（不健康）-5（很健康）"
    )

    created_at = models.DateTimeField(auto_now_add=True)
    views = models.IntegerField("浏览数", default=0)
    made_count = models.IntegerField("做过次数", default=0)
    is_recommended = models.BooleanField("手动推荐", default=False)  # 手动推荐

    def __str__(self):
        return self.title

class RecipeImage(models.Model):
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name="images")
    image = models.ImageField(upload_to="recipe_images/")

    def __str__(self):
        return f"Image for {self.recipe.title}"
